<template>
    <view>
        <!-- pages/setphone/index.wxml -->
        <view v-if="next == 0">
            <view class="phonebox">
                <view class="flexbox b-b">
                    <view class="mr-20">
                        <image class="icon-28-36 t-4" :src="imgUrl + 'setphone-icon.png'"></image>
                    </view>
                    <view>
                        <input disabled maxlength="11" class="widthinput" type="number" data-type="mobile" :value="mobile" placeholder="请输入手机号码" />
                    </view>
                </view>
                <view class="flexbox-sb">
                    <view class="centers">
                        <image class="icon-30-36 mr-20" :src="imgUrl + 'phone-code.png'"></image>
                        <input data-type="phoneCode" @input="onChangeType" @blur="onChangeType" class="widthinput" type="number" placeholder="请输入验证码" maxlength="6" />
                    </view>
                    <view @tap.stop.prevent="getCode" v-if="btnvisible == true" class="btn">| 获取验证码</view>
                    <view v-if="btnvisible == false" class="btn" :disabled="true">| {{ count_down }}S重新获取</view>
                </view>
            </view>
            <view class="msg-tabs" @tap.stop.prevent="onTabs">原号码无法使用</view>
            <view class="okbtn" @tap.stop.prevent="goNext">下一步</view>
        </view>

        <view v-if="next == 1">
            <view class="phonebox">
                <view class="flexbox b-b">
                    <view class="mr-20">
                        <image class="icon-28-36 t-4" :src="imgUrl + 'setphone-icon.png'"></image>
                    </view>
                    <view>
                        <input
                            data-type="newMobile"
                            @input="onChangeType"
                            @blur="onChangeType"
                            maxlength="11"
                            class="widthinput"
                            type="number"
                            :value="newMobile"
                            placeholder="请输入新手机号码"
                        />
                    </view>
                </view>
                <view class="flexbox-sb">
                    <view class="centers">
                        <image class="icon-30-36 mr-20" :src="imgUrl + 'phone-code.png'"></image>
                        <input data-type="newphoneCode" @input="onChangeType" @blur="onChangeType" class="widthinput" type="number" placeholder="请输入验证码" maxlength="6" />
                    </view>
                    <view @tap="getCode" v-if="newbtnvisible == true" class="btn">| 获取验证码</view>
                    <view v-if="newbtnvisible == false" class="btn" :disabled="true">| {{ newcount_down }}S重新获取</view>
                </view>
            </view>
            <view class="text-msg mt-20">更换手机号后，下次登录请使用新的号码登录</view>
            <view class="text-msg">当前手机号：{{ mobile }}</view>
            <view class="okbtn" @tap.stop.prevent="onSub">完成</view>
        </view>

        <view v-if="next == 2">
            <view class="phonebox">
                <view class="flexbox-sb">
                    <view class="centers">
                        <image class="icon-28-36 mr-20" :src="imgUrl + 'setpaypassword-icon.png'"></image>
                        <input
                            data-type="newPassword"
                            @input="onChangeType"
                            @blur="onChangeType"
                            maxlength="11"
                            class="widthinput"
                            type="number"
                            :value="newPassword"
                            placeholder="请输入支付密码"
                            :password="seeVisible"
                        />
                    </view>
                    <view class="centers">
                        <image @tap.stop.prevent="onSee" v-if="!seeVisible" class="icon-32" :src="imgUrl + 'see.png'"></image>
                        <image @tap.stop.prevent="onSee" v-if="seeVisible" class="icon-32" :src="imgUrl + 'nosee.png'"></image>
                    </view>
                </view>
            </view>
            <view class="text-msg password-msg">请输入您使用的支付密码进行验证</view>
            <view class="okbtn mt-200" @tap.stop.prevent="goNext">下一步</view>
        </view>
    </view>
</template>

<script>
// pages/setpassword/index.js
const app = getApp(); // 引入app

import _request from '../../utils/request.js';
export default {
    data() {
        return {
            imgUrl: app.globalData.imgUrl,

            //全局img路径
            btnvisible: true,

            count_down: 60,
            newbtnvisible: true,
            newcount_down: 60,
            mobile: '',

            // 旧手机号
            newMobile: '',

            // 新手机号
            phoneCode: '',

            // 旧手机号
            newphoneCode: '',

            // 新手机号
            next: 0,

            //
            newPassword: '',

            // 支付密码
            seeVisible: true,

            // 是否查看密码
            findObj: null,

            // 账户信息
            accountNumbet: 0,

            timer: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this; // 账户信息

        if (this.next == 0) {
            _request
                .get(
                    '/settings/accountSafe/find',
                    {
                        userId: uni.getStorageSync('userid')
                    },
                    'user'
                )
                .then((res) => {
                    if (res.data.code == 200) {
                        this.setData(
                            {
                                findObj: res.data.data,
                                mobile: res.data.data.mobile
                            },
                            () => {
                                that.getAccountNumber();
                            }
                        );
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        if (this.next == 1 || this.next == 2) {
            uni.redirectTo({
                url: '/pages/setphone/index'
            });
        } else if (this.next == 0) {
            uni.redirectTo({
                url: '/pages/myset/index'
            });
        }
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 获取用户账号数量
        getAccountNumber() {
            let vm = this;

            _request
                .get(
                    '/user/getAccountNumber',
                    {
                        mobile: vm.mobile
                    },
                    'user'
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        this.setData({
                            accountNumbet: res.data.data.accountNumbet
                        });

                        if (res.data.data.accountNumbet > 1) {
                            uni.showModal({
                                title: '',
                                showCancel: false,
                                content: '检测到您的手机号在意约其他端小程序有注册账号，现修改绑定手机号其他注册端口将一同变更，请谨慎修改!',
                                confirmText: '我知道了',

                                success(res) {
                                    if (res.confirm) {
                                    } else {
                                    }
                                }
                            });
                        }
                    } else {
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        // 是否查看明文
        onSee() {
            this.setData({
                seeVisible: !this.seeVisible
            });
        },

        // 校验验证码
        onphoneCodeCheck(mobile, phoneCode, type) {
            let vm = this;

            _request
                .postObj(
                    '/userSms/phoneCodeCheck',
                    {
                        userId: uni.getStorageSync('userid'),
                        mobile,
                        type,
                        phoneCode
                    },
                    'user'
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        uni.setNavigationBarTitle({
                            title: '修改手机号'
                        });

                        if (vm.next == 0) {
                            this.setData({
                                next: 1,
                                btnvisible: true,
                                count_down: 60
                            });
                        } else if (vm.next == 1) {
                            this.setData({
                                newbtnvisible: true,
                                newcount_down: 60
                            });
                            vm.updateUserMobile();
                        }
                    } else {
                        uni.showToast({
                            title: res.data.message || '验证失败!',
                            icon: 'error'
                        });
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        // 校验支付密码
        onpayCheck() {
            _request
                .postObj(
                    '/settings/checkPayWord',
                    {
                        userId: uni.getStorageSync('userid'),
                        payWord: this.newPassword
                    },
                    'user'
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        this.setData({
                            next: 1
                        });
                        uni.setNavigationBarTitle({
                            title: '修改手机号'
                        });
                    } else if (res.data.code == 2003) {
                        uni.showModal({
                            title: '您还未设置密码',
                            content: '请先设置密码',
                            confirmText: '前往设置',

                            success(res) {
                                if (res.confirm) {
                                    uni.navigateTo({
                                        url: '/pages/setpaypassword/index'
                                    });
                                } else if (res.cancel) {
                                }
                            }
                        });
                    } else {
                        uni.showToast({
                            title: res.data.message || '验证失败!',
                            icon: 'error'
                        });
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        // 切换密码验证
        onTabs() {
            this.setData(
                {
                    next: 2
                },
                () => {
                    _request
                        .get(
                            '/settings/initPayWord',
                            {
                                userId: uni.getStorageSync('userid')
                            },
                            'user'
                        )
                        .then((res) => {
                            if (res.data.message == '支付密码还未设置' && res.data.data == 0) {
                                uni.showModal({
                                    title: '您还未设置密码',
                                    content: '请先设置密码',
                                    confirmText: '前往设置',

                                    success(res) {
                                        if (res.confirm) {
                                            uni.navigateTo({
                                                url: '/pages/setpaypassword/index'
                                            });
                                        } else if (res.cancel) {
                                        }
                                    }
                                });
                            }
                        });
                }
            );
            uni.setNavigationBarTitle({
                title: '密码验证'
            });
        },

        // 下一步
        goNext() {
            const { phoneCode, newphoneCode, mobile, newMobile, next } = this;
            let vm = this;

            switch (next) {
                case 0:
                    if (phoneCode) {
                        vm.onphoneCodeCheck(mobile, phoneCode, 11);
                    } else {
                        uni.showToast({
                            title: '请输入验证码',
                            icon: 'none',
                            duration: 1000
                        });
                    }

                    break;

                case 2:
                    vm.onpayCheck();
                    break;

                default:
                    break;
            }
        },

        // 完成
        onSub() {
            const { phoneCode, newphoneCode, mobile, newMobile, next } = this;

            if (newMobile.length != 11) {
                uni.showToast({
                    title: '请输入正确手机号码',
                    icon: 'none',
                    duration: 'none'
                });
                return;
            } else if (!newphoneCode) {
                uni.showToast({
                    title: '请输入验证码',
                    icon: 'none',
                    duration: 'none'
                });
                return;
            } else {
                this.onphoneCodeCheck(newMobile, newphoneCode, 12);
            }
        },

        updateUserMobile() {
            _request
                .postObj(
                    '/user/updateUserMobile',
                    {
                        newMobile: this.newMobile,
                        userId: uni.getStorageSync('userid')
                    },
                    'user'
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        uni.showToast({
                            title: '更新成功,请重新登录！',
                            icon: 'none',
                            duration: 1000
                        });
                        this.setData({
                            next: 4
                        });
                        setTimeout(() => {
                            uni.clearStorage();
                            uni.reLaunch({
                                //清除所有的历史页面
                                url: '/pages/login/index'
                            });
                        }, 1000);
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none',
                            duration: 1000
                        });
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        // 获取手机号
        onChangeType(e) {
            const { type } = e.currentTarget.dataset;

            switch (type) {
                case 'mobile':
                    this.setData({
                        mobile: e.detail.value.replace(/\s+/g, '')
                    });
                    break;

                case 'phoneCode':
                    this.setData({
                        phoneCode: e.detail.value.replace(/\s+/g, '')
                    });
                    break;

                case 'newMobile':
                    this.setData({
                        newMobile: e.detail.value.replace(/\s+/g, '')
                    });
                    break;

                case 'newphoneCode':
                    this.setData({
                        newphoneCode: e.detail.value.replace(/\s+/g, '')
                    });
                    break;

                case 'newPassword':
                    this.setData({
                        newPassword: e.detail.value.replace(/\s+/g, '')
                    });
                    break;

                default:
                    break;
            }
        },

        // 手机验证码
        getCode(e) {
            let mobile = '';
            let type = '';
            const { next } = this;

            switch (next) {
                case 0:
                    mobile = this.mobile;
                    type = 11;
                    break;

                case 1:
                    mobile = this.newMobile;
                    type = 12;
                    break;

                default:
                    break;
            }

            if (this.mobile == this.newMobile) {
                uni.showToast({
                    title: '手机号未改变，请重新输入！',
                    icon: 'none',
                    duration: 1000
                });
                return;
            }

            _request
                .postObj(
                    '/userSms/getPhoneCode',
                    {
                        mobile,
                        // userId: wx.getStorageSync('userid'),
                        type
                    },
                    'user'
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        this.get_code_settime();
                    } else if (res.data.code === 408) {
                        uni.showModal({
                            title: '提示',
                            content: res.data.message,
                            confirmText: '我知道了',
                            showCancel: false
                        });
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none',
                            duration: 1000
                        });
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        //验证码按钮倒计时方法
        get_code_settime() {
            var that = this;
            let next = that.next;
            let countDown = next == 0 ? that.count_down : that.newcount_down; //获取倒计时初始值

            that.setData({
                //这里把setInterval复制给变量名timer
                timer: setInterval(function () {
                    // 每隔一秒减1
                    countDown--;

                    if (next == 0) {
                        that.setData({
                            btnvisible: false,
                            //此处用于隐藏验证码点击按钮，使倒计时显示
                            count_down: countDown //倒计时计数
                        });
                    } else {
                        that.setData({
                            newbtnvisible: false,
                            //此处用于隐藏验证码点击按钮，使倒计时显示
                            newcount_down: countDown //倒计时计数
                        });
                    } //当计数为0时，清空定时器，使验证码按钮再次显示

                    if (countDown == 0) {
                        clearInterval(that.timer); //清除timer，

                        if (next == 0) {
                            that.setData({
                                btnvisible: true,
                                //此处用于隐藏验证码点击按钮，使倒计时显示
                                count_down: '60' //倒计时计数
                            });
                        } else {
                            that.setData({
                                newbtnvisible: true,
                                //此处用于隐藏验证码点击按钮，使倒计时显示
                                newcount_down: '60' //倒计时计数
                            });
                        }
                    }
                }, 1000)
            });
        }
    }
};
</script>
<style>
/* pages/setphone/index.wxss */
page {
    background: #fbfbfb;
}

/* 输入框 */
.phonebox {
    width: 710rpx;
    background: #ffffff;
    box-shadow: 1px 1px 4px 1px rgba(241, 241, 241, 0.4);
    border-radius: 5px;
    margin: 20rpx 20rpx 0 20rpx;
    padding: 0 20rpx;
    box-sizing: border-box;
}

.label-class {
    font-size: 32rpx;
}

.flexbox {
    display: flex;
    flex-wrap: wrap;
    align-content: space-around;
    height: 120rpx;
}

.flexbox-sb {
    height: 120rpx;
}

.btn {
    border: 0 !important;
    font-size: 28rpx !important;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ff8722 !important;
    line-height: 120rpx;
}

/* 提交按钮 */

.okbtn {
    width: 710rpx;
    height: 84rpx;
    background: #ff8722;
    border-radius: 21px;
    margin: 0 20rpx;
    text-align: center;
    color: white;
    line-height: 84rpx;
    font-size: 32rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    margin-top: 80rpx;
}

.icon-28-36 {
    width: 28rpx;
    height: 36rpx;
}

.t-4 {
    position: relative;
    top: 4rpx;
}
.icon-30-36 {
    width: 30rpx;
    height: 36rpx;
}
.b-b {
    border-bottom: 1px solid #dadada;
}

.text-msg {
    font-size: 28rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 40rpx;
    margin-left: 40rpx;
}

.msg-tabs {
    margin: 20rpx 20rpx 0 20rpx;
    text-align: right;
    width: 710rpx;
    font-size: 28rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 40rpx;
}

.mt-200 {
    margin-top: 200rpx;
}

.password-msg {
    margin-top: 20rpx;
}
</style>
